package cn._51doit.flink.day02.sources;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.ParallelSourceFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.Random;

/**
 * 自定义Source（并行的Source）
 * 第一种，实现ParallelSourceFunction接口
 * 第二种，继承RichParallelSourceFunction抽象类
 *
 *
 */
public class CustomParSource1 {

    public static void main(String[] args) throws Exception {

        Configuration configuration = new Configuration();
        configuration.setInteger("rest.port", 8081);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(configuration);

        DataStreamSource<String> nums = env.addSource(new MyParSource());

        System.out.println("实现ParallelSourceFunction自定义的Source的并行度: " + nums.getParallelism());
        nums.print();
        env.execute();



    }

    private static class MyParSource implements ParallelSourceFunction<String> {

        boolean flag = true;

        @Override
        public void run(SourceContext<String> ctx) throws Exception {
            Random random = new Random();
            while (flag) {
                Thread.sleep(2000);
                ctx.collect(random.nextInt() + "");
            }
        }

        @Override
        public void cancel() {
            flag = false;
        }
    }

}
